<?php

namespace V1\Controller;

use Common\Library\Exception\BadRequest;

class UserController extends BaseController
{

    protected $errorCode = array(
        'register' => array(
            '-1' => '未知错误',
            '-2' => '验证码失效',
            '-3' => '手机号已经存在',
        ),
        'login' => array(
            '-1' => '用户不存在',
            '-2' => '密码错误',
            '-3' => '安全提示问答错误',
        ),
        'setpassword' => array(
            '-1' => '用户签名失效',
        ),
        'forgetpassword' => array(
            '-1' => '手机号未注册',
            '-2' => '验证码失效',
        ),
        'heatbeat' => array(
            '-1' => '用户签名失效',
        ),
        'logout' => array(
            '-1' => '用户签名失效',
        ),
        'avatar' => array(
            '-1' => '用户签名失效',
            '-2' => '上传图片不存在',
            '-3' => '上传图片太大',
            '-4' => '上传图片类型不对',
            '-5' => '同名文件已经存在了',
            '-6' => '移动文件出错',
        ),
        'nickname' => array(
            '-1' => '用户签名失效',
        ),
    );

    /**
     * 登录
     * @throws \Api\Library\Exception\BadRequest
     */
    public function login()
    {

        if (!IS_POST) {
            throw new BadRequest("该方法只支持POST请求", 1);
        }
        $data = array("code" => 0, "msg" => "", "info" => array());

        $phonenumber = I('n', '', '/^\d{11}$/');
        $password = I('p', '', '/^\w{32,64}$/');
        $user_token = I('user_token', '');
        
        $result = array();
        if (!empty($user_token)) {
            //判断user_token是否有效 
            $sessionModel = D('UserSession');
            $uid = $sessionModel->checkExpireTime($user_token);
            if (!empty($uid)) {
                $fields = ['id', 'nickname', 'password', 'phonenumber', 'avatar', 'money', 'experience'];
                $result = M('User')->where("id={$uid} and status=1")->field($fields)->find();
                !empty($result) && $data['user_token'] = $user_token;
                //$data['user_token'] = $sessionModel->getUserToken($result['id']);
            }
        } else if (empty($phonenumber) || empty($password)) {
            throw new BadRequest("参数异常", 1);
        }

        if (empty($result)) {
            $userModel = D('User');
            /* todo 只返回需要的字段 */
            $result = $userModel->login($phonenumber, $password);
        }

        if (is_array($result)) {
            $data['info'] = $result;
            if (empty($data['user_token'])) {
                $sessionModel = D('UserSession');
                $sessionModel->writeUserSession($result['id']);
                $data['user_token'] = $sessionModel->getUserToken($result['id']);
            }
            $data['info']['unread_msg_count'] = M('CommonMessage')->where(array('userid' => $result['id'], 'status' => 1, 'send_time' => 0))->count();
            $this->responseResult($data);
        } else {
            $this->responseError($result);
        }
    }

    /**
     * 注册
     */
    public function register()
    {
        if (!IS_POST) {
            throw new BadRequest("该方法只支持POST请求", 1);
        }
        $data = array("code" => 0, "msg" => "", "info" => array());

        $phonenumber = I('post.n', '', '/^\d{11}$/');
        $code = I('post.d', '', '/^\d{4}$/');

        if (empty($phonenumber) || empty($code)) {
            throw new BadRequest("参数异常", 1);
        }

        //验证码是否在有效期
        $smsModel = D('Sms');
        $isExpireSmsCode = $smsModel->checkExpireSmsCode($phonenumber, $code);

        empty($isExpireSmsCode) && $this->responseError(-2);

        $userModel = D('User');
        $isExistPhoneNumber = $userModel->checkPhoneNumber($phonenumber);

        empty($isExistPhoneNumber) && $this->responseError(-3);

        //注册用户，密码设置为空
        $uid = $userModel->register($phonenumber);
        $uid < 0 && $this->responseError(-1);

        add_task('register', $uid, 0, '注册奖励');
        
        //奖励推荐人
        $recommenderId = I('recommenderId', null);
        if(!empty($recommenderId)) {
	       add_task('invite', $recommenderId, 0,  '推荐好友奖励');
	       D('Friends')->addFriend($recommenderId, $uid, 2);
        }
        //获取user_token
        $sessionModel = D('UserSession');
        $sessionModel->writeUserSession($uid);
        $data['user_token'] = $sessionModel->getUserToken($uid);
        $this->responseResult($data);
    }

    /**
     * 设置完成密码后，登录系统
     */
    public function setPassword()
    {
        if (!IS_POST) {
            throw new BadRequest("该方法只支持POST请求", 1);
        }
        $data = array("code" => 0, "msg" => "", "info" => array());


        $password = I('p', '', '/^\w{32,64}$/');

        if (empty($password)) {
            throw new BadRequest("参数异常", 1);
        }

        list($uid, $user_token) = $this->checkUserToken(false);

        $userModel = D('User');
        $userModel->updateFiled($password, $uid); //更新密码
        $userModel->updateFiled(1, $uid, 4); //更新用户状态

        /* todo 只返回需要的字段 */
        //$result = $userModel->where("id={$uid}")->find();
        //$data['info'] = $result;

        $data['user_token'] = $user_token;
        $this->responseResult($data);
    }

    /**
     * 找回密码
     */
    public function forgetPassword()
    {
        if (!IS_POST) {
            throw new BadRequest("该方法只支持POST请求", 1);
        }
        $data = array("code" => 0, "msg" => "", "info" => array());

        $phonenumber = I('post.n', '', '/^\d{11}$/');
        $code = I('post.d', '', '/^\d{4}$/');
        $password = I('post.p', '', '/^\w{32,64}$/');

        if (empty($phonenumber) || empty($code) || empty($password)) {
            throw new BadRequest("参数异常", 1);
        }

        //验证码是否在有效期
        $smsModel = D('Sms');
        $isExpireSmsCode = $smsModel->checkExpireSmsCode($phonenumber, $code);
        empty($isExpireSmsCode) && $this->responseError(-2);

        $userModel = D('User');
        $isExistPhoneNumber = $userModel->checkPhoneNumber($phonenumber);

        $isExistPhoneNumber && $this->responseError(-1);

        $uid = $userModel->getUidByPhoneNumber($phonenumber);
        $userModel->updateFiled($password, $uid); //更新密码
        $this->responseResult($data);
    }

    /**
     * 心跳--自动续期
     */
    public function heatbeat()
    {
        if (!IS_POST) {
            throw new BadRequest("该方法只支持POST请求", 1);
        }
        $data = array("code" => 0, "msg" => "", "info" => array());

        list($uid, $user_token) = $this->checkUserToken();

        //更新用户session
        $sessionModel = D('UserSession');
        $sessionModel->updateExpiresTime($uid, $user_token);

        $unread_msg_count =   M('CommonMessage')->where(array('user_id' => $uid, 'status' => 1, 'send_time' => 0))->count();
        $follow_stock_count = M('UserStock')->where(array('user_id' => $uid, 'status' => 1,))->count();
        $money = M('User')->where(array('id' => $uid, 'status' => 1,))->getField('money');

        $data['info']['unread_msg_count'] = intval($unread_msg_count)  ;
        $data['info']['follow_stock_count'] = intval($follow_stock_count);
        $data['info']['money'] = intval($money);
        
        $this->responseResult($data);
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        if (!IS_POST) {
            throw new BadRequest("该方法只支持POST请求", 1);
        }
        $data = array("code" => 0, "msg" => "", "info" => array());


        list($uid, $user_token) = $this->checkUserToken();

        //获取user_token
        $sessionModel = D('UserSession');
        $where = array(
            'user_id' => $uid,
            'token' => $user_token,
        );
        $sessionModel->where($where)->save(array('expires_time' => NOW_TIME));
        $this->responseResult($data);
    }
    /**
     * 修改头像
     */
    public function avatar()
    {
        if (!IS_POST) {
            throw new BadRequest("该方法只支持POST请求", 1);
        }
        $data = array("code" => 0, "msg" => "", "info" => array());


        $file = $_FILES["avatar"];

        if (empty($file)) {
            throw new BadRequest("参数异常", 1);
        }

        list($uid, $user_token) = $this->checkUserToken();

       
           $uptypes = array(
                'image/jpg',
                'image/jpeg',
                'image/png',
                'image/pjpeg',
                'image/gif',
                'image/bmp',
                'image/x-png'
            );

            $max_file_size = 4000000;     //上传文件大小限制, 单位BYTE  
            $destination_folder = "./Uploads/Avatar/"; //上传文件路径          
            if (!is_uploaded_file($file[tmp_name])) {//是否存在文件 
               $this->responseError('-2');
            }

            
            if ($max_file_size < $file["size"]) {//检查文件大小
               $this->responseError('-3');
            }

            if (!in_array($file["type"], $uptypes)) {//检查文件类型
                $this->responseError('-4');
            }

            if (!file_exists($destination_folder)) {
                mkdir($destination_folder);
            }

            $filename = $file["tmp_name"];
            $image_size = getimagesize($filename);
            $pinfo = pathinfo($file["name"]);
            $ftype = $pinfo['extension'];
            $destination = $destination_folder . time() . "." . $ftype;
            if (file_exists($destination) && $overwrite != true) {
                 $this->responseError('-5');
            }

            if (!move_uploaded_file($filename, $destination)) {
               $this->responseError('-6');
            }

            $pinfo = pathinfo($destination);
            $newAvatar = '/Avatar/'.$pinfo[basename];
            //保存到数据库库中
            $userModel = D('User');
            $userModel->updateFiled($newAvatar, $uid,5); //更新密码
            
            $data['msg']='上传头像成功';
            $data['info']['avatar']=$newAvatar;
            $this->responseResult($data);
    }

    /**
     * 修改昵称
     */
    public function nickname()
    {
        if (!IS_POST) {
            throw new BadRequest("该方法只支持POST请求", 1);
        }
        $data = array("code" => 0, "msg" => "", "info" => array());


        $nickname = I('nickname','');

        if (empty($nickname)) {
            throw new BadRequest("参数异常", 1);
        }

        list($uid, $user_token) = $this->checkUserToken();

        //保存到数据库库中
        $userModel = D('User');
        $userModel->updateFiled($nickname, $uid,3); //更新密码

        $data['msg']='修改昵称成功';
        $data['info']['nickname']=$nickname;
        $this->responseResult($data);
    }
}
